﻿using System;
using System.Collections.Generic;
using System.Web.Services;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using Adex;
using Telerik.Web.UI;
using MediaMonitor.Common;
using System.Web.Security;
using System.Configuration;
using System.Drawing;
using Telerik.Charting;
using System.Transactions;
using SubSonic;
using System.Net.Mail;
using OfficeOpenXml;
using OfficeOpenXml.Drawing.Chart;
using System.Text;
using System.Net;

namespace MediaMonitor.Users
{
    public partial class NewAll_newsalertPending : Adex.BasePage
    {
        string appemailPassword = "";
        private static string AppName = ConfigurationManager.AppSettings["AppName"].ToString();
        private static string AdminEmail = ConfigurationManager.AppSettings["AdminEmail"].ToString();
        protected void Page_Load(object sender, EventArgs e)
        {
            string decryptpwd = string.Empty;
            UTF8Encoding encodepwd = new UTF8Encoding();
            Decoder Decode = encodepwd.GetDecoder();
            byte[] todecode_byte = Convert.FromBase64String(Request.Cookies["App"]["Password"].ToString());
            int charCount = Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);
            char[] decoded_char = new char[charCount];
            Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);
            appemailPassword = new String(decoded_char);

            hdnUserID.Value = Request.Cookies["User"]["UserName"].ToString();
            hdnUserName.Value = Request.Cookies["User"]["UserID"].ToString();
            hdnUserRole.Value = Request.Cookies["User"]["UserRole"].ToString();
            if (!IsPostBack)
            {
                if (Request.QueryString["code"].ToString() != "")
                {
                    ViewState["code"] = Request.QueryString["code"].ToString();
                    bindChart(Request.QueryString["code"].ToString());
                    if (Request.QueryString["code"].ToString() != "pending")
                    {
                        imgHead.ImageUrl = "../images/" + Request.QueryString["code"].ToString() + "-head.png";
                    }
                    else
                    {
                        imgHead.ImageUrl = "../images/media-head.png";
                    }
                    DataTable dtToday = SPs.NewsAlertPendingCount(Convert.ToInt32(Request.Cookies["User"]["UserID"].ToString()), Request.Cookies["User"]["Company"].ToString(), ViewState["code"].ToString(), "", "", "", "", "").GetDataSet().Tables[0];
                    if (Convert.ToInt32(dtToday.Rows[0][1]) > 0 || Convert.ToInt32(dtToday.Rows[1][1]) > 0 || Convert.ToInt32(dtToday.Rows[2][1]) > 0 || Convert.ToInt32(dtToday.Rows[3][1]) > 0)
                    {
                        bool flag;
                        Color[] green = new Color[] { Color.Gray, Color.Green, Color.LightPink, Color.Orange };
                        Color[] barColors = green;
                        RadChart1.Visible = true;
                        this.RadChart1.PlotArea.XAxis.AxisLabel.Visible = false;
                        this.RadChart1.PlotArea.XAxis.AutoScale = false;
                        this.RadChart1.PlotArea.XAxis.AddRange(1, 4, 1);
                        RadChart1.DataSource = dtToday;
                        RadChart1.DataBind();
                        int i = 0;
                        IEnumerator<ChartSeriesItem> enumerator = this.RadChart1.Series[0].Items.GetEnumerator();
                        try
                        {
                            while (true)
                            {
                                flag = enumerator.MoveNext();
                                if (!flag)
                                {
                                    break;
                                }
                                ChartSeriesItem item = enumerator.Current;
                                int num = i;
                                i = num + 1;
                                item.Appearance.FillStyle.MainColor = barColors[num];
                            }
                        }
                        finally
                        {
                            flag = enumerator == null;
                            if (!flag)
                            {
                                enumerator.Dispose();
                            }
                        }
                        this.RadChart1.PlotArea.XAxis[0].TextBlock.Text = dtToday.Rows[0][1].ToString();
                        this.RadChart1.PlotArea.XAxis[1].TextBlock.Text = dtToday.Rows[1][1].ToString();
                        this.RadChart1.PlotArea.XAxis[2].TextBlock.Text = dtToday.Rows[2][1].ToString();
                        this.RadChart1.PlotArea.XAxis[3].TextBlock.Text = dtToday.Rows[3][1].ToString();
                        this.RadChart1.Skin = "BlueStripes";
                    }
                    else { RadChart1.Visible = false; }
                    DataTable dt = SPs.NewaAlertPending(Convert.ToInt32(Request.Cookies["User"]["UserID"].ToString()), Request.Cookies["User"]["Company"].ToString(), "", Request.QueryString["code"].ToString(), "").GetDataSet().Tables[0];
                    ViewState["DataTAble"] = dt;
                    if (dt.Rows.Count > 0)
                    {
                        RadListView1.DataSource = dt;
                        RadListView1.DataBind();
                        lblNoRecord.Visible = false;
                        foreach (DataRow row in dt.Rows)
                        {
                            newspending(Convert.ToInt32(row["ID"].ToString()), Convert.ToInt32(Request.Cookies["User"]["UserID"].ToString()));
                        }
                    }
                    else
                    {
                        RadListView1.Visible = false;
                        lblNoRecord.Visible = true;
                        lblNoRecord.Text = "No Record Found";
                    }

                }
                else
                {
                    string code = "";
                    string count = "";
                    if (Request.Cookies["Last"]["TV"] != "" || Request.Cookies["Last"]["Press"] != "" || Request.Cookies["Last"]["Radio"] != "" || Request.Cookies["Last"]["Internet"] != "")
                    {

                        if (Request.Cookies["Last"]["TV"] != "" && Request.Cookies["Last"]["TV"] != null)
                        {
                            code += Request.Cookies["Last"]["TV"] + ",";
                            count += "'" + Request.Cookies["Last"]["TV"] + "',";
                        }
                        if (Request.Cookies["Last"]["Press"] != "" && Request.Cookies["Last"]["Press"] != null)
                        {
                            code += Request.Cookies["Last"]["Press"] + ",";
                            count += "'" + Request.Cookies["Last"]["Press"] + "',";
                        }
                        if (Request.Cookies["Last"]["Radio"] != "" && Request.Cookies["Last"]["Radio"] != null)
                        {
                            code += Request.Cookies["Last"]["Radio"] + ",";
                            count += "'" + Request.Cookies["Last"]["Radio"] + "',";
                        }
                        if (Request.Cookies["Last"]["Internet"] != "" && Request.Cookies["Last"]["Internet"] != null)
                        {
                            code += Request.Cookies["Last"]["Internet"];
                            count += "'" + Request.Cookies["Last"]["Internet"] + "',";
                        }
                    }
                    code = code.TrimEnd(',');
                    ViewState["code"] = code;
                    bindChart(code);
                    DataTable dtToday = SPs.NewsAlertPendingCount(Convert.ToInt32(Request.Cookies["User"]["UserID"].ToString()), Request.Cookies["User"]["Company"].ToString(), "iNMEDIA", Request.Cookies["Last"]["TV"], Request.Cookies["Last"]["Radio"], Request.Cookies["Last"]["Internet"], Request.Cookies["Last"]["Press"], count.TrimEnd(',')).GetDataSet().Tables[0];
                    if (Convert.ToInt32(dtToday.Rows[0][1]) > 0 || Convert.ToInt32(dtToday.Rows[1][1]) > 0 || Convert.ToInt32(dtToday.Rows[2][1]) > 0 || Convert.ToInt32(dtToday.Rows[3][1]) > 0)
                    {
                        bool flag;
                        Color[] green = new Color[] { Color.Gray, Color.Green, Color.LightPink, Color.Orange };
                        Color[] barColors = green;
                        RadChart1.Visible = true;
                        this.RadChart1.PlotArea.XAxis.AxisLabel.Visible = false;
                        this.RadChart1.PlotArea.XAxis.AutoScale = false;
                        this.RadChart1.PlotArea.XAxis.AddRange(1, 4, 1);
                        RadChart1.DataSource = dtToday;
                        RadChart1.DataBind();
                        int i = 0;
                        IEnumerator<ChartSeriesItem> enumerator = this.RadChart1.Series[0].Items.GetEnumerator();
                        try
                        {
                            while (true)
                            {
                                flag = enumerator.MoveNext();
                                if (!flag)
                                {
                                    break;
                                }
                                ChartSeriesItem item = enumerator.Current;
                                int num = i;
                                i = num + 1;
                                item.Appearance.FillStyle.MainColor = barColors[num];
                            }
                        }
                        finally
                        {
                            flag = enumerator == null;
                            if (!flag)
                            {
                                enumerator.Dispose();
                            }
                        }
                        this.RadChart1.PlotArea.XAxis[0].TextBlock.Text = dtToday.Rows[0][1].ToString();
                        this.RadChart1.PlotArea.XAxis[1].TextBlock.Text = dtToday.Rows[1][1].ToString();
                        this.RadChart1.PlotArea.XAxis[2].TextBlock.Text = dtToday.Rows[2][1].ToString();
                        this.RadChart1.PlotArea.XAxis[3].TextBlock.Text = dtToday.Rows[3][1].ToString();
                        this.RadChart1.Skin = "BlueStripes";
                    }
                    else { RadChart1.Visible = false; }
                    DataTable dt = SPs.NewaAlertPending(Convert.ToInt32(Request.Cookies["User"]["UserID"].ToString()), Request.Cookies["User"]["Company"].ToString(), "", code, "").GetDataSet().Tables[0];
                    //DataTable dt = SPs.NewaAlertLast(Request.Cookies["User"]["Company"].ToString(),code).GetDataSet().Tables[0];
                    if (dt.Rows.Count > 0)
                    {
                        RadListView1.DataSource = dt;
                        RadListView1.DataBind();
                        lblNoRecord.Visible = false;
                        imgHead.ImageUrl = "../images/media-head.png";
                        foreach (DataRow row in dt.Rows)
                        {
                            newspending(Convert.ToInt32(row["ID"].ToString()), Convert.ToInt32(Request.Cookies["User"]["UserID"].ToString()));
                        }
                    }
                    else
                    {
                        RadListView1.Visible = false;
                        lblNoRecord.Visible = true;
                        lblNoRecord.Text = "No Record Found";
                        imgHead.ImageUrl = "../images/media-head.png";
                    }
                }
            }
        }
        public void bindChart(string code)
        {
            bool flag;
            Color[] green = new Color[] { Color.Green, Color.Red, Color.Blue };
            Color[] barColors = green;
            DataTable dt = SPs.NewsalertPendingCalificacion(Convert.ToInt32(Request.Cookies["User"]["UserID"].ToString()), Request.Cookies["User"]["Company"].ToString(), code).GetDataSet().Tables[0];
            ChartAvenueReport.DataSource = dt;
            ChartAvenueReport.DataBind();
            ViewState["dt11"] = dt;
            flag = (!(dt.Rows[0][1].ToString() == "0") || !(dt.Rows[1][1].ToString() == "0") ? true : !(dt.Rows[2][1].ToString() == "0"));
            bool flag1 = flag;
            if (!flag1)
            {
                this.ChartAvenueReport.Visible = false;
            }
            this.ChartAvenueReport.PlotArea.XAxis.AxisLabel.Visible = false;
            int i = 0;
            this.ChartAvenueReport.PlotArea.XAxis.AutoScale = false;
            this.ChartAvenueReport.PlotArea.XAxis.AddRange(1, 3, 1);
            IEnumerator<ChartSeriesItem> enumerator = this.ChartAvenueReport.Series[0].Items.GetEnumerator();
            try
            {
                while (true)
                {
                    flag1 = enumerator.MoveNext();
                    if (!flag1)
                    {
                        break;
                    }
                    ChartSeriesItem item = enumerator.Current;
                    int num = i;
                    i = num + 1;
                    item.Appearance.FillStyle.MainColor = barColors[num];
                }
            }
            finally
            {
                flag1 = enumerator == null;
                if (!flag1)
                {
                    enumerator.Dispose();
                }
            }
            this.ChartAvenueReport.PlotArea.XAxis[0].TextBlock.Text = dt.Rows[0][1].ToString();
            this.ChartAvenueReport.PlotArea.XAxis[1].TextBlock.Text = dt.Rows[1][1].ToString();
            this.ChartAvenueReport.PlotArea.XAxis[2].TextBlock.Text = dt.Rows[2][1].ToString();
            this.ChartAvenueReport.Skin = "DeepGreen";
        }
        public void newspending(int ID, int UID)
        {
            TransactionOptions options = new TransactionOptions();
            options.Timeout = new TimeSpan(0, 2, 0);
            options.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted;
            TransactionScope ts = new TransactionScope(TransactionScopeOption.Suppress, options);
            try
            {
                SharedDbConnectionScope conn = new SharedDbConnectionScope(ConfigurationManager.ConnectionStrings["DBAdex"].ToString());
                try
                {
                    try
                    {

                        TblPendingNews prLog = new TblPendingNews();
                        prLog.NewsID = ID;
                        prLog.UserID = UID;

                        prLog.Save();

                        ts.Complete();


                    }
                    catch (Exception exception)
                    {
                        // ex2 = exception;
                        ts.Dispose();
                        conn.Dispose();
                    }
                }
                finally
                {

                    ((IDisposable)conn).Dispose();

                }
            }
            finally
            {

                ((IDisposable)ts).Dispose();

            }
        }
        protected void ddlSortNews_SelectedIndexChanged(object sender, EventArgs e)
        {
            string text = this.ddlSortNews.SelectedItem.Text;
            DataTable dt = null;
            ViewState["text"] = text;
            switch (text)
            {
                case "Media Type":
                    DataTable dataTable = (DataTable)ViewState["DataTAble"];
                    DataView dv1 = dataTable.DefaultView;
                    dv1.Sort = "MediaTypeName asc";
                    RadListView1.DataSource = dv1;
                    RadListView1.DataBind();
                    // dt = SPs.NewaAlertPending(Convert.ToInt32(Request.Cookies["User"]["UserID"].ToString()), Request.Cookies["User"]["Company"].ToString(), "", ViewState["code"].ToString(), "MediaTypeName asc").GetDataSet().Tables[0];
                    break;
                case "Title":
                    DataTable dataTable1 = (DataTable)ViewState["DataTAble"];
                    DataView dv = dataTable1.DefaultView;
                    dv.Sort = "Title asc";
                    RadListView1.DataSource = dv;
                    RadListView1.DataBind();
                    // dt = SPs.NewaAlertPending(Convert.ToInt32(Request.Cookies["User"]["UserID"].ToString()), Request.Cookies["User"]["Company"].ToString(), "", ViewState["code"].ToString(), "Title asc").GetDataSet().Tables[0];
                    break;
                case "Chronological":
                    DataTable dataTable2 = (DataTable)ViewState["DataTAble"];
                    DataView dv2 = dataTable2.DefaultView;
                    dv2.Sort = "RFDate asc";
                    RadListView1.DataSource = dv2;
                    RadListView1.DataBind();
                    //dt = SPs.NewaAlertPending(Convert.ToInt32(Request.Cookies["User"]["UserID"].ToString()), Request.Cookies["User"]["Company"].ToString(), "", ViewState["code"].ToString(), "RFdate asc").GetDataSet().Tables[0];
                    break;
                case "Most Recent":
                    DataTable dataTable3 = (DataTable)ViewState["DataTAble"];
                    DataView dv3 = dataTable3.DefaultView;
                    dv3.Sort = "RFDate desc";
                    RadListView1.DataSource = dv3;
                    RadListView1.DataBind();
                    //dt = SPs.NewaAlertPending(Convert.ToInt32(Request.Cookies["User"]["UserID"].ToString()), Request.Cookies["User"]["Company"].ToString(), "", ViewState["code"].ToString(), "RFDate desc").GetDataSet().Tables[0];
                    break;
            }
            //if (dt.Rows.Count > 0)
            //{
            //    RadListView1.DataSource = dt;
            //    RadListView1.DataBind();
            //    lblNoRecord.Visible = false;

            //}
            //else
            //{
            //    RadListView1.Visible = false;
            //    lblNoRecord.Visible = true;
            //    lblNoRecord.Text = "No Record Found";
            //}
        }
        public bool ifTrue(object val)
        {
            return (val == null) ? false : val.ToString().Equals("TV");

        }
        public bool ifPreshTrue(object val)
        {
            return (val == null) ? false : val.ToString().Equals("Press");

        }
        public bool ifRadioTrue(object val)
        {
            return (val == null) ? false : val.ToString().Equals("Radio");

        }
        public bool ifInternetTrue(object val)
        {
            return (val == null) ? false : val.ToString().Equals("Internet");

        }

        public string checkComment(string commentCount)
        {
            return (Convert.ToInt32(commentCount) > 0) ? "../images/chat-icon2.png" : "../images/chat-icon.jpg";
        }

        protected void btnSearch_click(object sender, EventArgs e)
        {
            SendMail(txtSendEmail.Text.ToString(), hdnID.Value.ToString(), txtSubject.Text, txtEmailBody.Text, txtSentby.Text);
            addressBook(txtSendEmail.Text.ToString());
            string script = "alert(\"Your news has been shared!\");";
            ScriptManager.RegisterStartupScript(this, this.GetType(), "ServerControlScript", script, true);

        }
        protected void imgbtnShareVideo1_click(object sender, EventArgs e)
        {
            string link = "";
            switch (hdnMediaTypeName.Value)
            {
                case "TV":
                    link = Utility.AppPath + "/sitefiles/NewsAlertvideo.aspx?SectionCode=" + hdnSectionCode.Value + "&t=f&ID=" + hdnShareVedioID.Value.Trim();

                    break;
                case "Radio":
                    link = Utility.AppPath + "/sitefiles/NewsAlertradio.aspx?SectionCode=" + hdnSectionCode.Value + "&t=f&ID=" + hdnShareVedioID.Value.Trim();
                    break;
                case "Press":
                    link = Utility.AppPath + "/sitefiles/NewsAlertpress.aspx?ID=" + hdnShareVedioID.Value + "&t=s&file=" + hdnImageAudioVideoName.Value.Trim();
                    break;
                case "Internet":
                    link = Utility.AppPath + "/sitefiles/Internet.aspx?ID=" + hdnShareVedioID.Value + "&t=s&file=" + hdnImageAudioVideoName.Value.Trim();
                    break;
            }
            SendmailForVedio(txtEmailForShareVideo.Text, hdnShareVedioID.Value, link, txtShareSubject.Text, txtShareEmailBody.Text, txtShareSentBy.Text);
            addressBook(txtEmailForShareVideo.Text.ToString());
            string script = "alert(\"Your clip has been shared!\");";
            ScriptManager.RegisterStartupScript(this, this.GetType(), "ServerControlScript", script, true);



            //SendmailForVedio(String users, string ID, string link);
        }
        public void addressBook(string email)
        {
            TransactionOptions options = new TransactionOptions();
            options.Timeout = new TimeSpan(0, 2, 0);
            options.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted;
            TransactionScope ts = new TransactionScope(TransactionScopeOption.Suppress, options);
            try
            {
                SharedDbConnectionScope conn = new SharedDbConnectionScope(ConfigurationManager.ConnectionStrings["DBAdex"].ToString());
                try
                {
                    try
                    {

                        TblAddressbok prLog = new TblAddressbok();
                        prLog.EmailID = email;
                        //prLog.UserID = UID;

                        prLog.Save();

                        ts.Complete();


                    }
                    catch (Exception exception)
                    {
                        // ex2 = exception;
                        ts.Dispose();
                        conn.Dispose();
                    }
                }
                finally
                {

                    ((IDisposable)conn).Dispose();

                }
            }
            finally
            {

                ((IDisposable)ts).Dispose();

            }

        }
        private void SendMail(String Users, string ID, string subject, string emailBody, string from)
        {
            string[] str = emailBody.Split(',');
            String msg = str[0] + "<br/>" + char.ToUpper(from[0]) + from.Substring(1) + " " + str[1] + "<br/><br/><br/><a href='" + Utility.AppPath + "/ShareNews.aspx?Code=" + ID + "'>Click here to view</a>";

            String title = subject;
            String toAccount = Users;
            //String toAccount = "niteshguleria@nascenture.com";
            String MyHost = ConfigurationManager.AppSettings["SMTPHost"].ToString();
            String MySMTPPort = ConfigurationManager.AppSettings["SMTPPort"].ToString();
            String MySMTPSSL = ConfigurationManager.AppSettings["SMTPSSL"].ToString();
            String fromAddr = AdminEmail;   //Email Address of Sender
            MailMessage smtpMssg = new MailMessage();
            smtpMssg.From = new MailAddress(fromAddr);
            if (toAccount.Contains(","))
            {
                string[] tos = toAccount.Split(',');
                for (int i = 0; i < tos.Length; i++)
                {
                    if (tos[i] == "," || tos[i] == "")
                    {
                    }
                    else
                    {
                        smtpMssg.To.Add(new MailAddress(tos[i].Replace(",", "")));
                    }
                }
            }
            else
            {
                smtpMssg.To.Add(new MailAddress(toAccount));
            }
            smtpMssg.Subject = title;
            smtpMssg.Body = msg;
            smtpMssg.IsBodyHtml = true;
            System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient(MyHost, Convert.ToInt32(MySMTPPort));
            smtpClient.Credentials = new NetworkCredential(Request.Cookies["App"]["Email"].ToString(), appemailPassword);
            smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
            if (MySMTPSSL == "true")
            {
                smtpClient.EnableSsl = true;
            }

            try
            {
                smtpClient.Send(smtpMssg);
            }
            catch (Exception ex)
            {
                throw new Exception("Email not sent | Reason: [" + ex.Message + "]");
            }
        }
        private void SendmailForVedio(String users, string ID, string link, string subject, string emailBody, string from)
        {
            string[] str = emailBody.Split(',');
            String msg = str[0] + "<br/>" + char.ToUpper(from[0]) + from.Substring(1) + " " + str[1] + "<br/><br/><br/><a href='" + link + "'>Click here to view</a>";

            String title = subject;
            String toAccount = users;
            //String toAccount = "niteshguleria@nascenture.com";
            String MyHost = ConfigurationManager.AppSettings["SMTPHost"].ToString();
            String MySMTPPort = ConfigurationManager.AppSettings["SMTPPort"].ToString();
            String MySMTPSSL = ConfigurationManager.AppSettings["SMTPSSL"].ToString();
            String fromAddr = AdminEmail;   //Email Address of Sender
            MailMessage smtpMssg = new MailMessage();
            smtpMssg.From = new MailAddress(fromAddr);
            if (toAccount.Contains(","))
            {
                string[] tos = toAccount.Split(',');
                for (int i = 0; i < tos.Length; i++)
                {
                    if (tos[i] == "," || tos[i] == "")
                    {
                    }
                    else
                    {
                        smtpMssg.To.Add(new MailAddress(tos[i].Replace(",", "")));
                    }
                }
            }
            else
            {
                smtpMssg.To.Add(new MailAddress(toAccount));
            }
            smtpMssg.Subject = title;
            smtpMssg.Body = msg;
            smtpMssg.IsBodyHtml = true;
            System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient(MyHost, Convert.ToInt32(MySMTPPort));
            smtpClient.Credentials = new NetworkCredential(Request.Cookies["App"]["Email"].ToString(), appemailPassword);
            smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
            if (MySMTPSSL == "true")
            {
                smtpClient.EnableSsl = true;
            }

            try
            {
                smtpClient.Send(smtpMssg);
            }
            catch (Exception ex)
            {
                throw new Exception("Email not sent | Reason: [" + ex.Message + "]");
            }

        }
        protected void btnComment_click(object sender, EventArgs e)
        {
            TransactionOptions options = new TransactionOptions();
            options.Timeout = new TimeSpan(0, 2, 0);
            options.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted;
            TransactionScope ts = new TransactionScope(TransactionScopeOption.Suppress, options);
            try
            {
                SharedDbConnectionScope conn = new SharedDbConnectionScope(ConfigurationManager.ConnectionStrings["DBAdex"].ToString());
                try
                {
                    try
                    {

                        if (hdncomentEditID.Value == "0")
                        {
                            TblComment prLog = new TblComment();
                            prLog.NewsID = new int?(Convert.ToInt32(hdnComentID.Value));
                            prLog.Comments = txtComent.Text;
                            prLog.RFDate = new DateTime?(DateTime.Now);
                            prLog.UserID = new int?(Convert.ToInt32(this.Request.Cookies["User"]["UserID"].ToString()));

                            prLog.Save();


                        }
                        else
                        {
                            TblComment.update(Convert.ToInt32(hdncomentEditID.Value), txtComent.Text, Convert.ToInt32(hdnComentID.Value));
                            hdncomentEditID.Value = "0";
                        }
                        ts.Complete();
                        txtComent.Text = string.Empty;

                    }
                    catch (Exception exception)
                    {
                        // ex2 = exception;
                        ts.Dispose();
                        conn.Dispose();
                    }
                }
                finally
                {

                    ((IDisposable)conn).Dispose();

                }
            }
            finally
            {

                ((IDisposable)ts).Dispose();

            }

            if (ViewState["text"] == null)
                ViewState["text"] = "";

            DataTable dt = SPs.NewaAlertPending(Convert.ToInt32(Request.Cookies["User"]["UserID"].ToString()), Request.Cookies["User"]["Company"].ToString(), "", Request.QueryString["code"].ToString(), ViewState["text"].ToString()).GetDataSet().Tables[0];
            RadListView1.DataSource = dt;
            RadListView1.DataBind();
        }
        public string color(object val)
        {
            string color = "";
            if (val.ToString() == "Positiva")
                color = "class='Positiva'";
            else if (val.ToString() == "Neutra")
                color = "class='Neutra'";
            else if (val.ToString() == "Negativa")
                color = "class='Negativa'";
            return color;

        }
        #region Web Form Designer generated code
        override protected void OnInit(EventArgs e)
        {
            //
            // CODEGEN: This call is required by the ASP.NET Web Form Designer.
            //
            InitializeComponent();
            InitializeComponent2();
            base.OnInit(e);
        }

        ///        Required method for Designer support - do not modify
        ///        the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.ChartAvenueReport.Click += new Telerik.Web.UI.RadChart.ChartClickEventHandler(this.RadChart1_Click);

        }
        private void InitializeComponent2()
        {
            this.RadChart1.Click += new Telerik.Web.UI.RadChart.ChartClickEventHandler(this.RadChart2_Click);
        }
        private void RadChart2_Click(object sender, ChartClickEventArgs args)
        {

            DataTable dataTable = (DataTable)ViewState["DataTAble"];
            DataView dv = dataTable.DefaultView;
            dv.RowFilter = "MediaTypeName='" + args.SeriesItem.Name + "'";
            RadListView1.DataSource = dv;
            RadListView1.DataBind();

        }
        private void RadChart1_Click(object sender, ChartClickEventArgs args)
        {
            DataTable dataTable = (DataTable)ViewState["DataTAble"];
            DataView dv = dataTable.DefaultView;
            dv.RowFilter = "Calification='" + args.SeriesItem.Name + "'";
            RadListView1.DataSource = dv;
            RadListView1.DataBind();
            //this.BindChartResult(this.ViewState["mediaTypeName"].ToString(), args.SeriesItem.Name);
        }
        #endregion
        protected void btnExport_Click(object sender, EventArgs e)
        {
            DataTable dtDetails = (DataTable)ViewState["DataTAble"];
            if (!dtDetails.Columns.Contains("Date"))
                dtDetails.Columns.Add("Date");
            if (dtDetails.Columns.Contains("RFDate"))
            {
                foreach (DataRow dr in dtDetails.Rows)
                {
                    string date = dr["RFDate"].ToString();
                    dr["Date"] = date.Substring(0, 10);
                    //dr["Date"] = String.Format("{0:dd.MM.yyyy}", dr["RFDate"]);
                }
            }
            if (dtDetails.Columns.Contains("ID"))
            {
                dtDetails.Columns.Remove("ID");
                dtDetails.Columns.Remove("MediaTypeName");
                dtDetails.Columns.Remove("MediaTypeCode");
                dtDetails.Columns.Remove("MediaCode");
                dtDetails.Columns.Remove("SectionCode");
                dtDetails.Columns.Remove("Totalrecord");


                dtDetails.Columns.Remove("RFDate");
            }
            DataTable tblcount = (DataTable)ViewState["dt11"];
            DumpSummary(dtDetails, tblcount);
        }
        protected void btnCALIFICACIONSave_click(object sender, EventArgs e)
        {
            TblComment.updateNewsCalificación(Convert.ToInt32(hdnlblCalification.Value), ddlCALIFICACION.SelectedItem.Text, "");
            string script = "myFunction('" + hdnlblCalification.Value + "','" + ddlCALIFICACION.SelectedItem.Text + "');";
            ScriptManager.RegisterStartupScript(this, this.GetType(), "ServerControlScript", script, true);
        }
        protected void btnIMPORTANCIASave_click(object sender, EventArgs e)
        {
            TblComment.updateNewsCalificación(Convert.ToInt32(hdnlblCalification.Value), "", ddlIMPORTANCIA.SelectedItem.Text);
            string script = "myFunction1('" + hdnlblCalification.Value + "','" + ddlIMPORTANCIA.SelectedItem.Text + "');";
            ScriptManager.RegisterStartupScript(this, this.GetType(), "ServerControlScript", script, true);
        }
        private void DumpSummary(DataTable tbldetails, DataTable tblChart)
        {

            Int32 tblColumnCount = tbldetails.Columns.Count;
            int row = tbldetails.Rows.Count;
            if (tblColumnCount > 0)
            {

                using (ExcelPackage pck = new ExcelPackage())
                {

                    try
                    {

                        //Create the worksheet
                        ExcelWorksheet ws = pck.Workbook.Worksheets.Add("News&Comments");


                        ws.Cells["A25"].LoadFromDataTable(tblChart, true);
                        ws.Cells["A30"].LoadFromDataTable(tbldetails, true);
                        ws.DefaultColWidth = 20;
                        using (ExcelRange rngSummary = ws.Cells["A1:D1"])
                        {
                            rngSummary.Style.Font.Bold = true;
                        }
                        using (ExcelRange rngUserSelection = ws.Cells["A25:O25"])
                        {
                            rngUserSelection.Style.Font.Bold = true;
                        }
                        var BarChart = ws.Drawings.AddChart("Competition Chart", eChartType.ColumnClustered) as ExcelBarChart;
                        //Set top left corner to row 1 column 2
                        BarChart.SetPosition(3, 2, 2, 2);
                        BarChart.SetSize(800, 400);
                        BarChart.Title.Text = "News & comments calification";
                        BarChart.Style = eChartStyle.Style26;
                        BarChart.Legend.Remove();
                        BarChart.DataLabel.ShowValue = true;
                        BarChart.DataLabel.Font.Bold = true;
                        BarChart.DataLabel.Border.LineCap = OfficeOpenXml.Drawing.eLineCap.Round;
                        BarChart.Series.Add(ExcelRange.GetAddress(26, 2, 28, 2), ExcelRange.GetAddress(26, 1, 28, 1));


                    }
                    catch { }
                    Response.Clear();
                    Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                    Response.AddHeader("content-disposition", "attachment;  filename=NewsAlert.xlsx");
                    Response.BinaryWrite(pck.GetAsByteArray());
                    Response.End();
                }
            }
        }
        [WebMethod]
        public static Bind[] GetNames(string IDN)
        {
            DataTable dt = SPs.getReportComment(IDN.ToString()).GetDataSet().Tables[0];
            List<Bind> list = new List<Bind>();

            foreach (DataRow row in dt.Rows)
            {
                Bind _names = new Bind();
                _names.ID = row["ID"].ToString();
                _names.Comments = row["Comments"].ToString();
                _names.NewsID = row["NewsID"].ToString();
                _names.RFDate = row["RFDate"].ToString();
                _names.UserID = row["UserID"].ToString();
                list.Add(_names);
            }
            return list.ToArray();
        }
    }


}
